package com.rachel.studyapp.mvp.model;

import android.content.Context;

import com.google.gson.Gson;
import com.rachel.studyapp.json.homejson.HomeRoot;
import com.rachel.studyapp.mvp.ContractUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhengshaorui on 2017/8/22.
 */

public class HomeModel {
    private Context mContext;
    private ContractUtils.IHomePresent mCallback;
    public HomeModel(Context context, ContractUtils.IHomePresent iHomePresent) {
        mContext = context;
        mCallback = iHomePresent;
    }

    public void handleJsonData(){
        //由于使用的是本地的json，所以这里获取 json数据就加载 assert 的json文件
        InputStream is = null;
        StringBuffer sb = null;
        try {
            is =  mContext.getResources().getAssets().open("home_data.json");
            int len = -1;
            byte[] bytes = new byte[1024];
            sb = new StringBuffer();
            while( (len = is.read(bytes)) != -1 ){
                sb.append(new String(bytes,0,len));
            }

            Gson gson = new Gson();
            HomeRoot root = gson.fromJson(sb.toString(), HomeRoot.class);

            mCallback.getJsonData(root);




        } catch (IOException e) {
            e.printStackTrace();
            mCallback.onFailure(e);

        }finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
